package dk.itu.spvc.tourtracker.gui;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import dk.itu.spvc.tourtracker.model.CurrentState;
import dk.itu.spvc.tourtracker.model.JSONServerResponse;
import dk.itu.spvc.tourtracker.model.NotePoint;
import dk.itu.spvc.tourtracker.model.Point;
import dk.itu.spvc.tourtracker.model.ResponseListener;
import dk.itu.spvc.tourtracker.model.Trip;
import dk.itu.spvc.tourtracker.service.ServiceLocalSQL;
import dk.itu.spvc.tourtracker.service.ServiceRemoteSQL;

public class TripLoadActivity extends Activity implements OnClickListener, OnItemClickListener, ResponseListener {

	// PRIVATE FIELDS

	// Debug
	private static final String TAG = "TourTracker";
	private static final boolean D = true;

	private ServiceRemoteSQL srvc_remote = ServiceRemoteSQL.getService();
	private ServiceLocalSQL srvc_local = ServiceLocalSQL.getService(this);
	private CurrentState currentState;
	List<Trip> allTrips = new ArrayList<Trip>();
	private ListView tripsListView;
	private Button dlRemote;

	// OVERRIDES

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.trips);
	}

	@Override
	protected void onStart() {
		super.onStart();

		dlRemote = (Button) findViewById(R.id.DownloadButton);
		dlRemote.setOnClickListener(this);

		currentState = srvc_local.getCurrentState();

		if (currentState == null) {
			// Cancel upload if no state - should never happen
			this.setResult(RESULT_CANCELED);
			finish();
		}

		tripsListView = (ListView) findViewById(R.id.ToursListView);
		
		tripsListView.setAdapter(new EfficientAdapter(this, allTrips));
		tripsListView.setOnItemClickListener(this);
		
		allTrips.clear();
		allTrips.addAll(srvc_local.getTrips(false));
	}

	public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
		int trip_local_id = allTrips.get(position).getTripId();

		if (trip_local_id != 0) {

			Intent intent = new Intent();
			intent.putExtra("trip_id", trip_local_id);

			setResult(RESULT_OK, intent);
			finish();

		} else {

			int trip_remote_id = allTrips.get(position).getTripRemoteId();
			srvc_remote.downloadTrip(trip_remote_id, this);

		}

		Log.d(TAG, "" + allTrips.get(position));
	}

	// BUTTON HANDLING

	public void onClick(View v) {

		if (v == findViewById(R.id.DownloadButton)) {

			allTrips.clear();
			allTrips.addAll(srvc_local.getTrips(false));
			srvc_remote.getTrips(this);
		}

	}

	public void onResponseReceived(HttpResponse response) {
		if (response != null) {

			JSONServerResponse res = new JSONServerResponse(response);

			if (!res.hasError()) {
				if (res.getAction().contentEquals("get_trips")) {

					List<Trip> remote_trips = res.getTrips();

					if (remote_trips != null) {

						allTrips.addAll(remote_trips);

						tripsListView.setAdapter(new EfficientAdapter(this, allTrips));

					} else {
						Toast.makeText(getBaseContext(), "Can't parse JSON data", Toast.LENGTH_SHORT).show();
					}

				} else if (res.getAction().contentEquals("get_trip_data")) {

					Trip trip = res.getTrip();
					List<Point> pathPoints = res.getTripPathPoints();
					List<NotePoint> notePoints = res.getTripNotePoints();

					if (trip != null) {
						if (pathPoints != null) {
							if (notePoints != null) {

								long tripId = srvc_local.addTrip(trip.getTripRemoteId(), trip.getTripName());
								boolean hasErrors = false;

								if (tripId != -1) {

									for (Point p : pathPoints) {
										long pointId = srvc_local.addPoint((int) tripId, p.getLongitude(), p.getLatitude(), p.getPointType());
										if (pointId == -1)
											hasErrors = true;
									}

									for (NotePoint p : notePoints) {
										long pointId = srvc_local.addPoint((int) tripId, p.getLongitude(), p.getLatitude(), p.getPointType());

										if (pointId != -1) {
											long noteId = srvc_local.addNote((int) pointId, (int) tripId, p.getNote().getText());
											if (noteId == -1)
												hasErrors = true;
										} else {
											hasErrors = true;
										}
									}
								} else {
									hasErrors = true;
								}

								if (!hasErrors) {
									allTrips.clear();
									allTrips.addAll(srvc_local.getTrips(false));
									srvc_remote.getTrips(this);
								} else {
									Toast.makeText(getBaseContext(), "Errors during adding a trip to the database", Toast.LENGTH_SHORT).show();
								}

							} else {
								Toast.makeText(getBaseContext(), "Can't parse note points JSON data", Toast.LENGTH_SHORT).show();
							}
						} else {
							Toast.makeText(getBaseContext(), "Can't parse path points JSON data", Toast.LENGTH_SHORT).show();
						}
					} else {
						Toast.makeText(getBaseContext(), "Can't parse Trip JSON data", Toast.LENGTH_SHORT).show();
					}

				}
			} else {
				Toast.makeText(getBaseContext(), res.getMessage(), Toast.LENGTH_SHORT).show();
			}

		} else {
			Toast.makeText(getBaseContext(), "Connection problem.", Toast.LENGTH_SHORT).show();
		}
	}

	private class EfficientAdapter extends BaseAdapter {
		private LayoutInflater mInflater;
		List<Trip> trips = null;

		public EfficientAdapter(Context context, List<Trip> trips) {
			mInflater = LayoutInflater.from(context);
			this.trips = trips;
		}

		public int getCount() {
			return trips.size();
		}

		public Object getItem(int position) {
			return position;
		}

		public long getItemId(int position) {
			return position;
		}

		public View getView(int position, View convertView, ViewGroup parent) {
			ViewHolder holder;
			if (convertView == null) {
				convertView = mInflater.inflate(R.layout.trip_item, null);
				holder = new ViewHolder();
				holder.text = (TextView) convertView.findViewById(R.id.TripListName);
				holder.text2 = (TextView) convertView.findViewById(R.id.TripListAction);

				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}

			holder.text.setText(""+trips.get(position).getTripName());
			
			
			if(trips.get(position).getTripId() != 0)
			{
				
				holder.text2.setBackgroundColor(Color.rgb(155, 255, 153));
				holder.text2.setText("Load");
			}
			else
			{
				holder.text2.setBackgroundColor(Color.rgb(255, 105, 51));
				holder.text2.setText("Download");
			}


			return convertView;
		}

		private class ViewHolder {
			TextView text;
			TextView text2;
		}
	}

}
